/**
 * @NApiVersion 2.x
 * @NScriptType Restlet
 * @NModuleScope SameAccount
 */
define(['N/http', 'N/https', 'N/record', 'N/search', 'N/runtime'],
/**
 * @param {http} http
 * @param {https} https
 * @param {record} record
 * @param {search} search
 */
function(http, https, record, search,runtime) {
   
   
    /**
     * Function called upon sending a GET request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.1
     */
    function doGet(requestParams) {
		log.debug('NO1','NO1')
		log.debug('no2','no2')
		log.debug('no3')
		log.debug('no4')
		log.debug('no4')
		log.debug('no4')

		log.debug('111111')

		log.debug('000000000000000000000')

    }

    /**
     * Function called upon sending a PUT request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPut(requestBody) {

    }
   
    /**
     * Function called upon sending a POST request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPost(requestBody) {
    	
    	
    	
    	log.error({
			title : '请求正文.',
			details : 'requestBody: ' + JSON.stringify(requestBody)
		});
    	var resultJson = {
    			 "status": "300",
			     "errMessage": "",
    			 "data": ""
    	};
    	
		try {
			log.debug('po',requestBody.po)
			log.debug('gr',requestBody.gr)
			if((requestBody.gr != '' && requestBody.gr !=null) || (requestBody.po !=''&& requestBody.po!= null)){
				try{
					var podata = getpodata(requestBody.gr,requestBody.po);
					log.debug('podata',podata)
					if(podata!= -1){
						resultJson.status = '300';
						resultJson.data = podata
					}else{
						resultJson.status = '900';
						resultJson.errMessage = '操作失败，该收货单/采购单没有对应的账单';
					}
				}catch(e){
					resultJson.status = '900';
					resultJson.errMessage = '操作失败，原因：'+e.message;

					log.debug('resultJson',resultJson);
				}



				return resultJson;
				
				
			}else {
				resultJson.status = '900';
				resultJson.errorMessage = '操作失败，po、gr不可都为空。';
				log.debug('resultJson',resultJson);

				return resultJson;
			}	
			
		} catch (e) {
			// TODO: handle exception
			resultJson.status = '900';
			resultJson.errorMessage = e.message;
			log.debug('e',e);
			log.debug('resultJson',resultJson);

			return resultJson;
		}
		
		
		

    }

    /**
     * Function called upon sending a DELETE request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doDelete(requestParams) {

    }

    function getpodata(grid,poid){
		var filter = [];
		var column = [];
		var data ;
		log.debug('getgr',grid)
		log.debug('getpo',poid)

		if(grid){
			filter.push(search.createFilter({
				name: 'numbertext',
				join:'custbody_dominos_filed_relatedgr',
				operator:search.Operator.IS,
				values:grid
			}))
			// filter.push(["type","anyof","VendBill"]);
			// filter.push('AND');
			// filter.push(["custbody_dominos_filed_relatedgr.numbertext","is","GR00083118"]);
			// filter.push('AND');
			// filter.push(["mainline","is","T"]);

		}
		if(poid){
			filter.push(search.createFilter({
				name: 'numbertext',
				join:'custbodyy_dominos_filed_polatedgr',
				operator:search.Operator.IS,
				values:poid
			}))

		}
		filter.push(search.createFilter({
			name: 'mainline',
			operator:search.Operator.IS,
			values:true
		}))

		column.push(search.createColumn({name:'internalid',summary:'group'}));
		var bill_search = search.create({
			type:'vendorbill',
			filters:filter,
			columns:column
		})
		log.debug('billsearch',bill_search)

		var bill_result = bill_search.run().getRange({start:0,end:100});
		log.debug('bill_result',bill_result)
		if(bill_result && bill_result.length > 0){
			data = [];
			for(var bill_i = 0;bill_i < bill_result.length;bill_i++){
				var billid = bill_result[bill_i].getValue({name:'internalid',summary:'group'});
				var billdata = getBillData(billid);
				data.push(billdata)
			}

		}else{
			data = -1;
		}
		return data;
	}
	function getBillData(bill_id){
    	var data ={};
    	var bill_record = record.load({type:'vendorbill',id:bill_id});
    	data.nsInternalid = bill_id
		data.transactionnumber = bill_record.getValue('transactionnumber');
		data.reference = bill_record.getValue('tranid');
		data.vendor = bill_record.getValue('entity');
		data.date = getDateString(bill_record.getValue('trandate'));
		data.duedate = getDateString(bill_record.getValue('duedate'));
		data.subsidiary = bill_record.getValue('subsidiary');
		data.currency = bill_record.getText('currency');
		data.exchangerate = bill_record.getValue('exchangerate');
		data.amount = bill_record.getValue('usertotal');
		data.tax = bill_record.getValue('taxtotal');
		data.relategr = subStringTran(bill_record.getText('custbody_dominos_filed_relatedgr'));
		data.relatepo = subStringTran(bill_record.getText('custbodyy_dominos_filed_polatedgr'));
		data.billstatus = bill_record.getValue('status');
		var relate_line = bill_record.getLineCount('links');
		var paytotle = 0;
		for(var link_i = 0;link_i < relate_line;link_i++){
			var link_type = bill_record.getSublistValue({sublistId:'links',fieldId:'type',line:link_i});
			if(link_type == 'Bill Payment'){
				var payamount =  bill_record.getSublistValue({sublistId:'links',fieldId:'total',line:link_i});
				paytotle = accAdd(paytotle,payamount)
			}
		}
		data.appliedamount = paytotle;
		return data
	}
	function getDateString(offsethour){
		var now = new Date(offsethour);
		var moffset = now.getTimezoneOffset();
		var t  = new Date(now.getTime() + ((8 * 60 + moffset) * 60 * 1000));
		//var t = new Date(now.getTime() + (offsethour * 60 * 60 * 1000));
		var year = t.getFullYear();
		var month = t.getMonth() + 1;
		var day = t.getDate();
		var hour = t.getHours();
		var minute = t.getMinutes();
		var second = t.getSeconds();

		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;
		hour = hour < 10 ? '0' + hour : hour;
		minute = minute < 10 ? '0' + minute : minute;
		second = second < 10 ? '0' + second : second;

		return year + '/' + month + '/' + day;
	}
	function subStringTran(cf){
    	if(cf != '' && cf != null){
			cf = cf.split(' ');
			cf = cf[cf.length-1];
			cf = cf.substring(1,cf.length);
		}
    	return cf;
	}
	function accAdd(arg1, arg2) {
		var r1, r2, m, c;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		c = Math.abs(r1 - r2);
		m = Math.pow(10, Math.max(r1, r2))
		if (c > 0) {
			var cm = Math.pow(10, c);
			if (r1 > r2) {
				arg1 = Number(arg1.toString().replace(".", ""));
				arg2 = Number(arg2.toString().replace(".", "")) * cm;
			} else {
				arg1 = Number(arg1.toString().replace(".", "")) * cm;
				arg2 = Number(arg2.toString().replace(".", ""));
			}
		} else {
			arg1 = Number(arg1.toString().replace(".", ""));
			arg2 = Number(arg2.toString().replace(".", ""));
		}
		return (arg1 + arg2) / m
	}


    return {
        'get': doGet,
        put: doPut,
        post: doPost,
        'delete': doDelete
    };
    
});
